package com.qf.controller;

import com.qf.utils.SYS;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@Controller
public class PicController  {


    @RequestMapping("/pic")
    protected void draw(HttpSession session, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("image/png");

        BufferedImage buffer=new BufferedImage(140,40,BufferedImage.TYPE_INT_RGB);

        Graphics g=buffer.getGraphics();

        g.setColor(Color.LIGHT_GRAY);

        Random r=new Random();

        g.fillRect(0,0,140,40);

        for (int i = 1; i <=30  ; i++) {
            g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
            g.drawLine(r.nextInt(140),r.nextInt(40),r.nextInt(140),r.nextInt(40));
        }
        g.setColor(new Color(r.nextInt(256),r.nextInt(256),r.nextInt(256)));
        g.setFont(new Font("黑体", Font.ITALIC,35));

        String checkCode=this.getRandomCode();

        g.drawString(checkCode,25,35);
        ImageIO.write(buffer,"png",resp.getOutputStream());

        session.setAttribute(SYS.CODE,checkCode.toUpperCase());

    }

    private String getRandomCode(){
        String  source="abcedfghjkmnpqrstuvwxyz23456789ABCDEFGHJKMNPQRSTUVWXYZ";
        StringBuffer str=new StringBuffer();
        Random r=new Random();
        for (int i = 1; i <=4 ; i++) {
            int local=r.nextInt(54);
            str=str.append(source.substring(local,local+1));
        }
        return str.toString();
    }

}
